package com.jt.aop;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.vo.SysResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
@Slf4j
@RestControllerAdvice //aop+异常通知
public class SystemException {

    //确定该请求是一个JSONP的跨域请求时,才按照指定的格式返回 callback=xxx
    @ExceptionHandler({RuntimeException.class, SQLException.class})//当遇到某种异常时才会执行
    public Object exception(Exception e, HttpServletRequest request){
        log.error(e.getMessage());
        e.printStackTrace();
        //如果出错返回系统接别的报错数据

        //1.获取callback的请求参数
        String callback = request.getParameter("callback");
        //2.判断是否为JSONP的跨域请求
        if (StringUtils.hasLength(callback)){//有值则是jsonp
            return new JSONPObject(callback, SysResult.fail());
        }else {
            return SysResult.fail();
        }

    }
}
